package com.thread;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * @author cxt
 * @date 2021/10/28
 * 多线程练习
 */
@Slf4j
public class Thread1 {
    static boolean flag = false;
//    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
//                lock.lock();
                try {
                    if (!flag) {
                        flag = true;
                        Thread.sleep(100);
                        log.info("t2改变状态" + i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
//                    lock.unlock();
                }
            }
        }, "t2").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
//                lock.lock();
                Thread currentThread = Thread.currentThread();
                try {
                    if (flag) {
                        flag = false;
                        currentThread.interrupt();
                        Thread.sleep(100);
                        log.info("t1打印" + i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
//                    lock.unlock();
                }
            }
        }, "t1").start();
    }

    private volatile boolean stop = false;

    @Test
    public void test() throws InterruptedException {
        Thread tt = new Thread(() -> {
            while (true) {
                if (stop) {
                    log.debug("tt结束运行，退出当前线程");
                    break;
                }
                log.info("tt运行中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "tt");

        tt.start();
        log.info("tt启动");
        Thread.sleep(2000);
        log.info("tt停止");
        stop = true;
    }

    @Test
    public void test1() {
        NewThread thread = new NewThread();
        thread.createThread();
        thread.createThread();
        thread.createThread();
        thread.createThread();
    }
}

class NewThread {
    // Balkeing 模式
    static boolean flag = false;

    public void createThread() {
        // synchronize 代码块中程序越多就越消耗性能，这里只需要关注读写flag的代码即可，其他不会影响
        synchronized (this) {
            if (flag) {
                return;
            }
            flag = true;
        }
        Thread monitor = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("监控系统资源！");
            }
        }, "monitor");
        monitor.start();
    }
}
